/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.saint.tvtest;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.saint.tvtest.Utils.AppUtils;
import com.saint.tvtest.Utils.HttpUtil;
import com.saint.tvtest.activity.Main2Activity;
import com.saint.tvtest.bean.DataBean;
import com.saint.tvtest.bean.MainBean;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/*
 * MainActivity class that loads {@link MainFragment}.
 */
public class MainActivity extends Activity {
    private Activity act;
    private RelativeLayout rlParent;
    private TextView tvBtn1, tvBtn2, tvBtn3, tvBtn4, tvBtn5, tvBtn6, tvBtn7, tvBtn8, tvBtn9;
    private TextView tvExit, tvContent;
    private Toast toast;
    private String url;
    private DataBean dataBean;
    private ImageView ivMianBg;
    private MediaPlayer mediaPlayer;
    String loadingFile = "file:///android_asset/bg.jpg";
    private View.OnFocusChangeListener onFocusChangeListener;
    private BitmapDrawable drawable;
    private Callback<String> callback;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        act = this;
        url = AppUtils.readAssetsTextReturnStr(this, "ip");
        initView();
        initListener();
        initCallBack();
        getMainData();
    }

    private void initView() {
        rlParent = findViewById(R.id.rl_parent);
        drawable = new BitmapDrawable(loadingFile);
        ivMianBg = findViewById(R.id.iv_main_bg);

        tvBtn1 = findViewById(R.id.tv_btn1);
        tvBtn2 = findViewById(R.id.tv_btn2);
        tvBtn3 = findViewById(R.id.tv_btn3);
        tvBtn4 = findViewById(R.id.tv_btn4);
        tvBtn5 = findViewById(R.id.tv_btn5);
        tvBtn6 = findViewById(R.id.tv_btn6);
        tvBtn7 = findViewById(R.id.tv_btn7);
        tvBtn8 = findViewById(R.id.tv_btn8);
        tvBtn9 = findViewById(R.id.tv_btn9);
        tvExit = findViewById(R.id.tv_exit);
        tvContent = findViewById(R.id.tv_content);

        Glide.with(act).load(loadingFile).into(ivMianBg);
        tvContent.setText(url);
    }


    private void initListener() {
        onFocusChangeListener = new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (view.hasFocus()) {
//                    tShort("getFocus: " + view.getId());
                    play();
                }
            }
        };

        tvBtn1.setOnFocusChangeListener(onFocusChangeListener);
        tvBtn2.setOnFocusChangeListener(onFocusChangeListener);
        tvBtn3.setOnFocusChangeListener(onFocusChangeListener);
        tvBtn4.setOnFocusChangeListener(onFocusChangeListener);
        tvBtn5.setOnFocusChangeListener(onFocusChangeListener);
        tvBtn6.setOnFocusChangeListener(onFocusChangeListener);

    }

    private void initCallBack() {
        callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful() && null != response.body()) {
//                    dataBean = new Gson().fromJson(response.body(), MainBean.class).getData();
//                    tvContent.setText(dataBean.toString());
//                    if (!TextUtils.isEmpty(dataBean.getCat_bg())) {
//                        Glide.with(act)
//                                .load(dataBean.getCat_bg())
//                                .placeholder(drawable)
//                                .error(drawable)
//                                .into(ivMianBg);
//
//                        tvBtn1.setText(dataBean.getCats().get(0).getName());
//                        tvBtn1.setTextColor(Color.parseColor("#" + dataBean.getCats().get(0).getName_color().getValue()));
//                        tvBtn2.setText(dataBean.getCats().get(1).getName());
//                        tvBtn2.setTextColor(Color.parseColor("#" + dataBean.getCats().get(1).getName_color().getValue()));
//
//                    }
                } else {
                    onFailure(call, new Throwable("response body is null"));
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                tShort("加载失败：" + t.getMessage());
                Log.e("LOADINGData", t.getMessage());
            }
        };
    }

    private void getMainData() {
        Call<String> call = HttpUtil.getInstance(url).requestMainBean();
        call.enqueue(callback);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
            tShort("key code :" + keyCode);
            if (tvBtn1.hasFocus()) {
                tShort("tvBtn1 onKEYDOWN" + keyCode);
                startActivity(new Intent(act, Main2Activity.class));
            } else if (tvBtn2.hasFocus()) {
                tShort("tvBtn2 onKEYDOWN" + keyCode);
            } else if (tvBtn3.hasFocus()) {
                tShort("tvBtn3 onKEYDOWN" + keyCode);
                Glide.with(act).load("file:///android_asset/bg.jpg").into(ivMianBg);
            } else if (tvBtn4.hasFocus()) {
                tShort("tvBtn4 onKEYDOWN" + keyCode);
            } else if (tvBtn5.hasFocus()) {
                tShort("tvBtn5 onKEYDOWN" + keyCode);
            } else if (tvBtn6.hasFocus()) {
                tShort("tvBtn6 onKEYDOWN" + keyCode);
            } else if (tvBtn7.hasFocus()) {
                tShort("tvBtn7 onKEYDOWN" + keyCode);
            } else if (tvBtn8.hasFocus()) {
                tShort("tvBtn8 onKEYDOWN" + keyCode);
            } else if (tvBtn9.hasFocus()) {
                tShort("tvBtn9 onKEYDOWN" + keyCode);
            } else if (tvExit.hasFocus()) {
                tShort("退出");
                finish();
            } else {
                return true;
            }

        }
//        tShort("移动时keyCode: " + keyCode + "  event: " + event.getAction());
//        if (KeyEvent.KEYCODE_DPAD_DOWN == keyCode) {
        play();
//            return true;
//        }
        return super.onKeyDown(keyCode, event);
    }

    public void tShort(String msg) {
        if (null == toast) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.setText(msg);
        }

        toast.show();

    }

    private void play() {
        try {
            //播放 assets/a2.mp3 音乐文件
            if (null == mediaPlayer) {
                AssetFileDescriptor fd = act.getAssets().openFd("favorite.wav");
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
                mediaPlayer.prepare();
            } else {
                mediaPlayer.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaPlayer.release();
    }


    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        return super.onGenericMotionEvent(event);
    }
}
